package wxdb.ui;


import java.awt.*;
import java.awt.event.*;

import javax.swing.*;


public class SelectDB extends JDialog{
	private String[] databases = new String[Global.UI_REGISTER_DBMAX];
	private JList databaseList;
	
	private JButton lgButton = new JButton("Login");
	
	private JLabel lgLabel = new JLabel("Select a DataBase to login :");

	private JPanel pane = new JPanel();
	
	private void setMyPane(){
		GridBagLayout gridbag = new GridBagLayout();
		GridBagConstraints constraints = new GridBagConstraints();
		pane.setLayout(gridbag);

		constraints=new GridBagConstraints();
		constraints.insets=new Insets(5,5,5,5);
		constraints.gridwidth=GridBagConstraints.REMAINDER;
		gridbag.setConstraints(lgLabel, constraints);
		pane.add(lgLabel);
		
		constraints=new GridBagConstraints();
		constraints.insets=new Insets(5,5,5,5);
		constraints.fill=GridBagConstraints.HORIZONTAL;
		constraints.gridwidth=GridBagConstraints.REMAINDER;
		gridbag.setConstraints(databaseList, constraints);
		pane.add(databaseList);

		constraints=new GridBagConstraints();
		constraints.insets=new Insets(5,5,5,5);
		constraints.anchor=GridBagConstraints.CENTER;
		gridbag.setConstraints(lgButton, constraints);
		pane.add(lgButton);
		
		setLocation(350,100);
		setContentPane(pane);
	}
	
	private void initListener(){
		ActListener actListener = new ActListener();
		lgButton.addActionListener(actListener);
	}
	
	class ActListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			if(e.getSource() == lgButton)
				lgButtonRun();
		}
	}
	
	private void lgButtonRun(){
		if(((String)databaseList.getSelectedValue())==null){
			JOptionPane.showMessageDialog(null,"Select your DB please","Error" ,JOptionPane.ERROR_MESSAGE);
			return;
		}
		Global.mg = new Management((String)databaseList.getSelectedValue());
		this.dispose();
	}
	
	public SelectDB(String username){
		databases = Global.getUserDatabases(username);
		if(databases[0]==null){
			CreateDB cdb = new CreateDB(username);
			this.dispose();
		}else{
			databaseList = new JList(databases);
			setTitle("Select DB");
			setSize(300,200);
			initListener();
			setMyPane();
			setVisible(true);
			setResizable(false);
		}
	}
}
